package com.dushibao.filter;

import com.dushibao.entity.User;
import com.dushibao.service.UserService;
import com.dushibao.service.impl.UserServiceImpl;
import com.dushibao.utils.CommUtils;
import com.dushibao.utils.SecurityHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "AuthorizationFilter",urlPatterns = "/*")
public class AuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        SecurityHolder.setContext(req,res);

        String requestUri = req.getRequestURI();
        String servletPath = req.getServletPath();

        List<String> exts = Arrays.asList("css","js","jpg","png","login","register","ico");

        //不拦截的请求:后缀是css、js、jpg、png,或者包含路径login、register的
        if(CommUtils.endWith(exts,servletPath)){
            chain.doFilter(request,response);
            return;
        }

        req.setCharacterEncoding("UTF-8");
        res.setContentType("text/html;charset=UTF-8");

        User user = (User) req.getSession().getAttribute("user");

        //如果session中有登录信息直接通过
        if(user != null){
            chain.doFilter(request,response);
            return;
        }

        //其他的请求都做拦截 只有登录成功的才能正常访问 否则访问login登录页面
        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
            String userName = null;
            String password = null;

            for (Cookie cookie : cookies) {
                if("userName".equals(cookie.getName())){
                    userName = URLDecoder.decode(cookie.getValue(),"UTF-8");
                }
                if("password".equals(cookie.getName())){
                    password = URLDecoder.decode(cookie.getValue(),"UTF-8");
                }
            }

            if(userName!=null && password!=null){
                UserService userService = new UserServiceImpl();
                List<User> users = userService.queryByUserNameAndPassword(userName,password);
                if(users!=null && users.size() == 1) {
                    req.getSession().setAttribute("user", users.get(0));
                    chain.doFilter(request,response);
                    return;
                }
            }

        }
        res.sendRedirect("/login");
    }


}
